<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--组织机构数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="organizationName"
            placeholder="请输入组织机构名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :highlight-current="true"
            :data="organizationDatas"
            :props="defaultProps"
            node-key="organizationId"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户姓名" prop="employeeName">
            <el-input
              v-model="queryParams.employeeName"
              placeholder="请输入用户姓名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="是否启用" prop="isEnable">
            <el-select
              v-model="queryParams.isEnable"
              placeholder="是否启用"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in isEnableStatus"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
            <el-button size="mini" @click="resetQuery">重置</el-button>
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" type="index" align="center" key="userId" v-if="columns[0].visible" />
          <el-table-column label="用户类型" align="center" prop="userType" key="userType" v-if="columns[1].visible" width="120">
            <template slot-scope="scope">
              <span>
                <el-tag type="danger" v-if="scope.row.userType === '0'">系统内置</el-tag>
                <el-tag type="warning" v-if="scope.row.userType === '1'">员工</el-tag>
                <el-tag  v-if="scope.row.userType === '2'">普通</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="用户名" align="center" key="userName" prop="userName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="用户姓名" align="center" key="employeeName" prop="employeeName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="组织机构" align="center" key="organizationName" prop="organizationName" v-if="columns[4].visible" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="employeeTel" prop="employeeTel" v-if="columns[5].visible" width="120" />
          <el-table-column label="是否启用" align="center" key="isEnable" v-if="columns[6].visible">
            <template slot-scope="scope">
              <el-switch
                :disabled="scope.row.userType==='0'"
                v-model="scope.row.isEnable"
                :active-value="activeData.activeValue"
                :inactive-value="activeData.inactiveValue"
                :active-color="activeData.activeColor"
                :inactive-color="activeData.inactiveColor"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[7].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userType !== '0'">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                v-if="scope.row.userType === '2'"
              >
                修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
                v-if="scope.row.userType === '2'"
              >
                删除
              </el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-if="scope.row.userType === '2'" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                    v-hasPermi="['system:user:resetPwd']">
                    重置密码
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
                v-if="scope.row.userType !== '2'"
              >
                重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          :total="total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getPageList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="组织机构" prop="organizationSysCode">
              <Treeselect
                v-model="form.organizationSysCode"
                :multiple="false"
                :options="organizationDatas"
                :flat="true"
                :normalizer="normalizer"
                placeholder="请选择组织机构"
                noOptionsText="无数据"
              >
              </Treeselect>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="2-20字符" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" :disabled="true">
                <el-option
                  v-for="item in userTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnable">
              <el-radio-group v-model="form.isEnable">
                <el-radio
                  v-for="item in isEnableStatus"
                  :key="item.value"
                  :label="item.value"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPageList,add,edit,resetUserPassword,checkNameIsUnique,getDetail,del} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { getOrganizationsSelectItems } from "@/api/organization/organization/organization.js";
import { isEnableStatus,userTypes,activeData} from "@/utils/constants/common/constants.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: [ 'sys_user_sex'],
  components: { Treeselect },
  data() {
    var nameValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkNameIsUnique({userName:value,userId:this.form.userId}).then(res =>{
          let isUnique = res.data
          if (isUnique) {
            return callback()
          }else{
            return callback(new Error('用户名不能重复'));
          }
        })
      }else{
         return callback(new Error('用户名不能为空'));
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      activeData:activeData,
      // 弹出层标题
      title: "",
      // 组织机构树选项
      organizationDatas: null,
      // 是否显示弹出层
      open: false,
      // 组织机构名称
      organizationName: null,
      isEnableStatus:isEnableStatus,
      userTypes:userTypes,
      // 表单参数
      form: {
        organizationSysCode:null,
        userId:null,
        userName:null,
        userType:userTypes[2].value,
        isEnable:'1',
        remark:null,
        roleIds:[]
      },
      defaultProps: {
        children: "children",
        label: "organizationName",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        employeeName: null,
        isEnable: null,
        organizationSysCode: null
      },
      // 列信息
      columns: [
        { key: 0, label: `编号`, visible: true },
        { key: 1, label: `用户类型`, visible: true },
        { key: 2, label: `用户名`, visible: true },
        { key: 3, label: `用户姓名`, visible: true },
        { key: 4, label: `组织机构`, visible: true },
        { key: 5, label: `手机号码`, visible: true },
        { key: 6, label: `是否启用`, visible: true },
        { key: 7, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        isEnable: [
          { required: true, message: "请选择是否启用", trigger: "blur" }
        ],
        organizationSysCode: [
          { required: true, message: "请选择组织机构", trigger: "change" },
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选组织机构树
    organizationName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getPageList();
    this.getTreeselect();
  },
  methods: {

    normalizer(node) {
      return {
        id: node.organizationSysCode,
        label: node.organizationName,
        children: node.children,
      }
    },
    /** 查询用户列表 */
    getPageList() {
      this.loading = true;
      getPageList(this.queryParams).then(res => {
          this.userList = res.data.records;
          this.userList.forEach(u => {
            u.employeeName = u.employeeName===null?'--':u.employeeName
            u.organizationName = u.organizationName===null?'--':u.organizationName
            u.employeeTel = u.employeeTel===null?'--':u.employeeTel
          })
          this.total = Number.parseInt(res.data.total)
          this.loading = false;
        }
      );
    },
    /** 查询组织机构下拉树结构 */
    getTreeselect() {
      getOrganizationsSelectItems().then(res => {
        let data =  res.data;
        this.organizationDatas = this.handleTree(data, "organizationId","organizationParentId");
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.organizationSysCode = data.organizationSysCode;
      this.getPageList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.isEnable === "1" ? "启用" : "停用";
      this.$confirm('是否'+text+'该用户？','确认信息',{
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(()=>{
        edit({userId:row.userId,isEnable:row.isEnable}).then(res =>{
          this.$message({
            type: 'success',
            message: text + "成功"
          })
          this.getPageList()
        })
      }).catch(action => {
        row.isEnable = row.isEnable === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        organizationSysCode:null,
        userId:null,
        userName:null,
        userType:userTypes[2].value,//只能新增普通用户（普通用户没有关联用户）
        isEnable:'1',
        remark:null,
        roleIds:[]
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getPageList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.organizationSysCode = null
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.title = '新增普通用户'
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDetail({userId:row.userId}).then(res => {
        this.form = res.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$confirm('是否重置当前用户密码？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false
      }).then(() => {
          resetUserPassword({userId:row.userId}).then(res => {
            this.$modal.msgSuccess("密码重置成功");
          });
        }).catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId !==null) {
            edit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getPageList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getPageList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否删除该用户？','确认信息',{
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(()=>{
        del(row.userId).then(res =>{
          this.$message({
            type: 'success',
            message: "删除成功"
          })
          this.getPageList()
        })
      }).catch(action => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getPageList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
